<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane
            label="角色管理"
            style="font-size: 18px"
          >
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd()"
              > 新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles" style="width:100%" border :default-sort="{prop: 'date', order: 'descending'}">
              <el-table-column
                sortable
                label="序号"
                type="index"
                width="100"
                :index="makeIndex"
              />
              <el-table-column sortable prop="name" label="角色名称" width="180" />
              <el-table-column sortable prop="description" label="描述" />
              <el-table-column sortable label="操作" width="300">
                <template v-slot="scope">
                  <el-button size="small" type="success">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(scope.row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(scope.row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :page-size="pageParams.pagesize"
                :current-page.sync="pageParams.page"
                layout="total,sizes,prev,pager,next,jumper"
                :total="total"
                :page-sizes="[2, 4, 6, 8, 10]"
                @size-change="doSizeChange"
                @current-change="hCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
        <!-- 新增弹框 -->
        <el-dialog
          :title="isEdit ? '编辑角色' : '新增角色'"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          :visible.sync="showDialog"
          @close="hClose"
        >
          <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="roleForm.name" />
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
              <el-input v-model="roleForm.description" />
            </el-form-item>
          </el-form>
          <!-- 底部 -->
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button size="small" @click="showDialog = false">取消</el-button>
              <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getRoles, deleteRole, addRole, updateRole } from '@/api/settings'
export default {
  data() {
    return {
      activeName: 'first',
      roles: [],
      // 是否编辑
      isEdit: false,
      pageParams: {
        page: 1, // 查询第一页
        pagesize: 4// 每页两条  --- 要与pagination中page-size一致
      },
      total: 0, // 总的数据条数,
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      // 校验
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // 请求列表数据
    this.loadRoles()
  },
  methods: {
  // 请求列表数据
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log(res)
        this.roles = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
      }
    },
    //  size发生变化
    doSizeChange(size) {
      console.log(size)
      // 修改每页数量
      this.pageParams.pagesize = size
      this.pageParams.page = 1 // 每页数量变化,页码恢复到1
      // 刷新列表
      this.loadRoles()
    },
    // 页面发生变化
    hCurrentChange(curPage) {
      console.log(curPage)
      // 更新页面
      this.pageParams.page = curPage
      this.loadRoles()
    },
    // 分页后页面index延续
    makeIndex(index) {
      return (this.pageParams.page - 1) * this.pageParams.pagesize + index + 1
    },
    // 封装删除的自定义组件
    async doDel(id) {
      try {
        const res = await deleteRole(id)
        console.log(res)
        this.$message.success('删除成功')
        // 2. 如果当前表格中只有一条，删除之后自动请求上一页数据
        if (this.roles.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        // 请求列表数据
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 删除
    hDel(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
        this.loadRoles()
      }).catch(() => {

      })
    },
    // 添加数据
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        console.log('添加数据', res)
        this.showDialog = false
        this.total++
        this.pageParams.page = Math.ceil(this.total / this.pageParams.pagesize)
        this.$message.success('添加成功')
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 编辑数据
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res)
        this.showDialog = false
        this.$message.success('编辑成功')
        this.loadRoles()
      } catch (err) {
        this.$message.error('编辑失败')
        console.log(err)
      }
    },
    // 点击编辑数据
    hEdit(row) {
      // 1. 把当前的数据直接给表单
      this.roleForm = { ...row }
      // 2. 显示弹层
      this.showDialog = true
      // console.log(row)
      // 3. 设为编辑状态
      this.isEdit = true
    },
    hAdd() {
      // 显示弹层
      this.showDialog = true
      // console.log(row)
      //  设为非编辑状态
      this.isEdit = false
    },

    // 用户点击了保存
    hSubmit() {
      console.log('提交')
      // 手动兜底校验
      this.isEdit ? this.doEdit() : this.doAdd()
    },
    hClose() {
      this.roleForm = { // 表单数据项
        name: '',
        description: ''
      }
      this.$refs.roleForm.resetFields()
    }
  }
}
</script>
